package com.nti56.springboot.exception;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
@ResponseBody
public class MyExceptionHandler {

    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> handlerMyException(MyException ex) {
        Map<String,Object> result = new HashMap<>();
        result.put("msg", ex.getMessage());
        result.put("error type", "MyException");
        return result;
    }

    @ExceptionHandler(MyRuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> handlerMyRuntimeException(MyRuntimeException ex) {
    	ex.printStackTrace();
        Map<String,Object> result = new HashMap<>();
        result.put("msg", ex.getMessage());
        result.put("error type", "MyRuntimeException");
        return result;
    }
    
    @ExceptionHandler(Exception.class)
    public ModelAndView error(Exception e){
        ModelAndView modelAndView = new ModelAndView();
        // 封装异常信息，用于页面的渲染
        modelAndView.addObject("exception", e.getClass().getName());
        // 转发到error.jsp 页面，进行错误提示
        modelAndView.setViewName("/error");
        return modelAndView;
    }
}
